import React, { Component } from 'react';
import { connect } from 'dva';
import { Form, Button, Modal, Input } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import SelectForm from '@/components/SelectForm';
import RightDraw from '@/components/RightDraw';
import AdSelect from '@/components/AdSelect';
import AdButton from '@/components/AdButton';
import ManageList from '@/components/ManageList';
import AntdFormItem from '@/components/AntdFormItem';
import AntdInput from '@/components/AntdInput';
import TableButtons from '@/components/TableButtons';
import StandardTable from '@/components/StandardTable';
import AdSearch from '@/components/AdSearch';
import { allDictList } from '@/utils/constans';
import SearchSelect from '@/components/SearchSelect';
import AntdDatePicker from '@/components/AntdDatePicker';
import { columnsUser, supplierColumns, columnsDriver } from '@/pages/Common/common';
import { vitifyCheck, queryPerson, queryDict, formateDateToMin, formatPrice } from '@/utils/common';
import CabinetOilDetail from './CabinetOilDetail';
import {
  allDispatchType,
  selectCabinetOilList,
  saveAllValues,
  renderTableAdSelect,
  codes,
  EmptyList,
  routeUrl,
} from './utils';
const { confirm } = Modal;
const dateFormat = 'YYYY-MM-DD';

@ManageList
@connect(({ cabinetOil, loading, component }) => ({
  trainInfoList: cabinetOil.trainInfoList,
  cabinetOilList: cabinetOil.cabinetOilList,
  formValues: cabinetOil.formValues,
  dictObject: component.dictObject,
  searchValue: component.searchValue,
  loading: loading.effects[allDispatchType.list],
}))
@Form.create()
export default class CabinetOilList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      expandForm: false,
      visible: false,
      detailId: '',
      selectedRows: [],
    };
    this.className = 'CabinetOil-table';
  }

  componentWillMount() {
    // 查询字典项
    const allDict = [allDictList.currencyType, allDictList.cabinetType,allDictList.oilWearType];
    queryDict({ props: this.props, allDict });
  }

  componentDidMount() {
    selectCabinetOilList({ props: this.props });
  }

  /**
   * form 查找条件 重置
   */
  handleFormReset = () => {
    const { form, formValues } = this.props;
    const props = { props: this.props };
    this.setState({
      selectedRows: [],
    });
    form.resetFields();
    saveAllValues({ payload: { formValues: {} }, ...props });
    selectCabinetOilList({ ...props });
  };

  /**
   * form 查找条件 查询
   */
  handleSearch = formValues => {
    // if (!formValues) return;
    console.log('formValues ===', formValues);
    const { ...param } = formValues;
    const params = { props: this.props, payload: param };
    saveAllValues({ payload: { formValues: param }, props: this.props });
    selectCabinetOilList(params);
  };

  /**
   * table 表格 分页操作
   */
  handleStandardTableChange = param => {
    const { formValues } = this.props;
    selectCabinetOilList({ payload: { ...formValues, ...param }, props: this.props });
  };

  // 查看详情
  showDetail = (e, record) => {
    e.stopPropagation();
    this.handleStateChange([{ detailId: record.id }, { visible: true }]);
  };

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };

  //新建
  handleAdd = () => {
    router.push(routeUrl.add);
  };

  //编辑
  handleEdit = () => {
    const { detailId } = this.state;
    this.handleStateChange([{ visible: false }]);
    router.push(`${routeUrl.edit}/${detailId}`);
  };

  columns = [
    {
      title: '柜型',
      dataIndex: 'cabinetType',
      render: (text, record) => {
        const content = renderTableAdSelect({
          props: this.props,
          value: text,
          key: allDictList.cabinetType,
        });
        return (
          <AdButton
            mode={'a'}
            onClick={e => this.showDetail(e, record)}
            text={content}
            code={codes.showDetail}
          />
        );
      },
      fixed: this.props.isMobile ? false : true,
    },
    {
      title: '是否放空',
      dataIndex: 'beEmpty',
      render: (text, record) => <AdSelect onlyRead={true} value={text} data={EmptyList} />,
      width: 100,
    },
    {
      title: '重量(大于等于)',
      dataIndex: 'weightStart',
      render: text => <span>{formatPrice(text)}</span>,
      width: 150,
    },
    {
      title: '重量(小于)',
      dataIndex: 'weightEnd',
      render: text => <span>{formatPrice(text)}</span>,
      width: 130,
    },
    {
      title: '标准油耗',
      dataIndex: 'standardOilWear',
      render: text => <span>{formatPrice(text)}</span>,
      width: 100,
    },
    {
      title: '油耗标准类型',
      dataIndex: 'oilWearType',
      // render: text => <span>{formatPrice(text)}</span>,
      render: text =>(
        <AdSelect
          data={this.props.dictObject[allDictList.oilWearType]}
          value={text}
          onlyRead={true}
          payload={{ code: allDictList.oilWearType }}
        />),
      width: 100,
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      render: text => <span title={text}>{text}</span>,
      width: 100,
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
    {
      title: '更新人',
      dataIndex: 'updateBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
  ];

  //删除
  removeCabinetOil = flag => {
    const { dispatch, formValues } = this.props;
    const { detailId, selectedRows } = this.state;
    confirm({
      title: '确定要删除这条数据吗？',
      content: ' ',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: allDispatchType.remove,
          payload: { ids: flag ? [detailId] : selectedRows.map(v => v.id) },
          callback: data => {
            if (!data) return;
            this.setState({ visible: false, selectedRows: [] });
            selectCabinetOilList({ props: this.props, payload: formValues });
          },
        });
      },
    });
  };

  getValue = (values, type) => {
    this.setState({
      [type]: values,
    });
  };
  render() {
    const { cabinetOilList, loading, form, isMobile, dictObject } = this.props;
    const { expandForm, detailId, visible, disabled, selectedRows } = this.state;

    const commonParams = {
      getFieldDecorator: form.getFieldDecorator,
    };
    const firstFormItem = (
      <AntdFormItem label="柜型" code="cabinetType" {...commonParams}>
        <AdSelect payload={{ code: allDictList.cabinetType }} />
      </AntdFormItem>
    );
    const secondFormItem = (
      <AntdFormItem label="放空" code="beEmpty" {...commonParams}>
        <AdSelect isExist={true} data={EmptyList} />
      </AntdFormItem>
    );

    const selectFormParams = {
      firstFormItem,
      secondFormItem,
      form,
      className: this.className,
      handleFormReset: this.handleFormReset,
      handleSearch: this.handleSearch,
      toggleForm: expandForm => {
        this.handleStateChange([{ expandForm }]);
      },
      code: codes.select,
    };

    const tableButtonsParams = {
      handleAdd: this.handleAdd,
      code: codes.add,
      pagination: cabinetOilList.pagination,
      buttons: (
        <AdButton
          disabled={!selectedRows.length > 0}
          onClick={() => this.removeCabinetOil()}
          text="删除"
          type="danger"
          ghost
          code={codes.remove}
        />
      ),
    };

    // 详情 参数
    const rightDrawParams = {
      isMobile,
      visible,
      title: '柜型标准油耗详情',
      code: codes.showDetail,
      closeDetail: this.handleStateChange.bind(this, [{ visible: false }]),
      buttons: (
        <>
          <AdButton
            onClick={() => this.removeCabinetOil(1)}
            text="删除"
            type="danger"
            ghost
            code={codes.remove}
          />
          <Button.Group style={{ marginLeft: 8 }}>
            <AdButton type="primary" onClick={this.handleEdit} text="编辑" code={codes.edit} />
          </Button.Group>
        </>
      ),
    };

    return (
      <>
        <SelectForm {...selectFormParams} />
        <TableButtons {...tableButtonsParams} />
        <StandardTable
          loading={loading}
          data={cabinetOilList}
          selectedRows={selectedRows}
          onSelectRow={selectedRows => {
            this.handleStateChange([{ selectedRows }]);
          }}
          columns={this.columns}
          onPaginationChange={this.handleStandardTableChange}
          expandForm={expandForm}
          className={this.className}
          code={codes.page}
        />
        <RightDraw {...rightDrawParams}>
          <CabinetOilDetail detailId={detailId} visible={visible} />
        </RightDraw>
      </>
    );
  }
}
